package com.snack.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snack.common.result.Result;
import com.snack.entity.dto.StoreDTO;
import com.snack.entity.pojo.Store;
import com.snack.entity.pojo.User;
import com.snack.mapper.StoreMapper;
import com.snack.service.StoreService;
import com.snack.service.UserService;
import com.snack.utils.UserIdThreadLocal;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author huangfuhao
 * @Date 2025/3/18
 */
@Service
@Slf4j
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {


    @Resource
    private UserService userService;

    @Override
    public Result addStore(Store store) {
        log.info("管理员新增店铺接口");
        save(store);
        return Result.success(store);
    }

    @Override
    public Result deleteStore(Store store) {

        log.info("管理员删除店铺接口");
        Long id = store.getId();
        boolean b = removeById(store);
        if (!b){
            return Result.error("删除失败");
        }
        return Result.success(id);
    }

    @Override
    public Result listStore() {

        List<StoreDTO> listDTO = new ArrayList<>();
        //获取店铺列表
        List<Store> list = list();
        log.info("{}", list);
        if (list == null || list.isEmpty()) {
            return Result.success(new ArrayList<>());
        }

        for (Store store : list) {//遍历每个店铺
            StoreDTO storeDTO = BeanUtil.copyProperties(store, StoreDTO.class);

            //获取店铺id
            Long storeId = store.getId();
            //根据店铺id查询该店铺的管理员
            User manager = userService.lambdaQuery().eq(User::getStoreId, storeId).eq(User::getRoleId, 2).one();
            storeDTO.setManger(manager);

            //查询该店铺拥有的员工
            Long count = userService.lambdaQuery().eq(User::getStoreId, storeId).count();
            storeDTO.setEmployeeNum(count.intValue());

            //将查询到的完整信息存放到listDTO
            listDTO.add(storeDTO);
        }


        //获取店铺下属管理员，员工数量等信息
        return Result.success(listDTO);
    }

    @Override
    public Result updateStore(Store store) {
        return null;
    }

    /**
     * 获取员工所在店铺的id
     * @return
     */
    @Override
    public Long getStoreIdByUser() {
        Long storeId = userService.lambdaQuery().eq(User::getId, UserIdThreadLocal.getUserId()).one().getStoreId();
        return storeId;
    }


}